package edu.cmu.cs214.hw9.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import java.util.Date;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextField;

import edu.cmu.cs214.hw9.facelook.Post;

public class ProfilePanel extends JPanel {

	private FacelookAppGUI container;
	private JTextField textField;
	
	//field that indicates whether the two users are friends.  If own profile, for all intents and purposes, yes
	//because you should see what a friend would see, and won't have to deal with requests
	private boolean friends;
	private boolean pending;
	//emailName is the name of the profile you are viewing, emailUser is the user accessing it
	public ProfilePanel(final String emailName, final String emailUser, FacelookAppGUI a) {
		super();
		container = a;
		this.setBackground(Color.decode("#3b5998"));
		this.setPreferredSize(new Dimension(770,539));
		setLayout(null);
		
		JLabel lblFacelook = new JLabel("Facelook");
		lblFacelook.setFont(new Font("Lucida Fax", Font.PLAIN, 32));
		lblFacelook.setForeground(Color.WHITE);
		lblFacelook.setBounds(12, 13, 199, 32);
		add(lblFacelook);
		
		final String name = container.getController().getName(emailName);
		//GET THE NAME THAT IS TIED TO THE EMAIL ADDRESS
		
		final String username = container.getController().getName(emailUser);
		//GET THE USERNAME THAT IS TIED TO THE EMAIL ADDRESS

		JLabel nameLabel = new JLabel(name);
		nameLabel.setForeground(Color.WHITE);
		nameLabel.setBounds(173, 17, 199, 32);
		nameLabel.setFont(new Font("Lucida Fax", Font.PLAIN, 21));
		add(nameLabel);
		
		
		JLabel lblLatest = new JLabel("Latest Posts");
		lblLatest.setFont(new Font("Lucida Fax", Font.PLAIN, 20));
		lblLatest.setForeground(Color.WHITE);
		lblLatest.setBounds(12, 87, 166, 40);
		add(lblLatest);
		
		JPanel panel = new JPanel();
		panel.setBounds(22, 147, 719, 379);
		add(panel);
		panel.setLayout(new GridLayout(5, 2, 5, 5));
		
		/*
		 * Fill this GridLayout with StatusPost buttons for the status/notifications
		 * It is ok to generate this at the beginning and only refresh when coming back to this page. 
		 * If there are less than 10 then leave the remainder of the grid blank. These don't need to link back to same page.
		 */
		
		ArrayList<Post> posts = new ArrayList<Post>();
		//if them be friends, or its your own page, get the profile feed
		//designed for friends
		if (container.getController().areFriends(emailName, emailUser, false)
				|| emailName.equals(emailUser))
			posts = (container.getController().getProfFeed(emailName, true));
		
		//if them not be friends, but viewer subscribes viewee, get profile feed
		//designed for subscribers
		else if (container.getController().isSubscribed(emailUser, emailName))
			posts = (container.getController().getProfFeed(emailName, false));
		
		//if not friends, post.size() is 0
		
		for(int i = 0; i<posts.size();i++)
		{
			StatusPost status = new StatusPost(emailName, 
					posts.get(i).getTimeStamp(), posts.get(i).getMessage());
			panel.add(status);
		}
		
		
		if(!emailUser.equals(emailName)){//Only show these when it is not your own profile
		JButton btnAddFriend = new JButton("Add/Remove Friend");
		btnAddFriend.setBounds(12, 49, 155, 25);
		add(btnAddFriend);
		
		
		//=====================================//
		btnAddFriend.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO FILL IN CODE TO ADD/REMOVE FRIEND
				//boolean variables to indicate whether them be friends, or
				//if viewer has been friend requested by viewee
				friends = container.getController().areFriends(emailName, emailUser, false);
				pending = container.getController().areFriends(emailName, emailUser, true);
				if (!friends) //NOT friends
				{
					if (pending) //viewee HAS friend requested viewer
					{
						//this means we make the two of them friends
						if(container.getController().acceptFriend(emailName, emailUser))
						{
							JOptionPane.showMessageDialog(container, "You are now friends with "+name+"!",
									"Friend Request Accepted", JOptionPane.PLAIN_MESSAGE);
						}
						else //not sure what would cause this, vague error message reflects this
							JOptionPane.showMessageDialog(container, "An Error has occured.  Please try again",
									"Facelook Error", JOptionPane.PLAIN_MESSAGE);
					}
					else //viewee has NOT friend requested viewer
					{	
						//this means viewer will friend request viewee
						if(container.getController().requestFriend(emailUser, emailName))
							JOptionPane.showMessageDialog(container, "Your request to "+name+" has been sent!",
								"Friend Request Sent", JOptionPane.PLAIN_MESSAGE);
						else
							JOptionPane.showMessageDialog(container, "Your request to "+name+" failed.",
									"Friend Request Failed", JOptionPane.PLAIN_MESSAGE);
					}
				}
				else //ARE friends
				{
					//this means hater is trying to unfriend victim
					int n = JOptionPane.showConfirmDialog(container, "Are you sure you want to unfriend "+name+"?",
						    "Unfriend Request", JOptionPane.YES_NO_OPTION);
					if (n == JOptionPane.YES_OPTION)
					{
						if(container.getController().removeFriend(emailName, emailUser))
						{
							JOptionPane.showMessageDialog(container, "You are no longer friends with "+name+".",
									"Friend Unfriended", JOptionPane.PLAIN_MESSAGE);
						}
						else //not sure what would cause this, vague error message reflects this
							JOptionPane.showMessageDialog(container, "An Error has occured.  Please try again",
									"Facelook Error", JOptionPane.PLAIN_MESSAGE);
					}
				}
			}
			
		});
		//=====================================//

		
		
		JButton btnAddSubscription = new JButton("Add/Remove Subscription");
		btnAddSubscription.setBounds(183, 49, 199, 25);
		add(btnAddSubscription);
		
		
		//=====================================//
		btnAddSubscription.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				//if they are friends, don't subscribe, because its redundant and wrong
				if (container.getController().areFriends(emailUser, emailName, false))
				{
					JOptionPane.showMessageDialog(container, "You are friends with "+name+".  You " +
							"can already view " + name + "'s notifications",
							"Subscription Notice", JOptionPane.PLAIN_MESSAGE);
					return;
				}
				boolean subd = container.getController().isSubscribed(emailUser, emailName);
				if (!subd) //if viewer is NOT subscribed to profile's user
				{
					//subscribe them
					if(container.getController().subscribeTo(emailUser, emailName))
					{
						JOptionPane.showMessageDialog(container, "You are now subscribed to "+name+"!",
								"Subscription Confirmation", JOptionPane.PLAIN_MESSAGE);
					}
					else //not sure what would cause this, vague error message reflects this
						JOptionPane.showMessageDialog(container, "An Error has occured.  Please try again",
								"Facelook Error", JOptionPane.PLAIN_MESSAGE);
					
				}
				else //viewer IS subscribed to user
				{
					//unsubscribe
					int n = JOptionPane.showConfirmDialog(container, "Are you sure you want to unsubscribe from "+name+"?",
						    "Unsubscription Request", JOptionPane.YES_NO_OPTION);
					if (n == JOptionPane.YES_OPTION)
					{
						if(container.getController().unSubscribe(emailUser, emailName))
						{
							subd = !subd;
							JOptionPane.showMessageDialog(container, "You are no subscribed to "+name+".",
									"Unsubscription Confirmed", JOptionPane.PLAIN_MESSAGE);
						}
						else //not sure what would cause this, vague error message reflects this
							JOptionPane.showMessageDialog(container, "An Error has occured.  Please try again",
									"Facelook Error", JOptionPane.PLAIN_MESSAGE);
					}
				}

		}
		});
		}
		//=====================================//

		
		JButton btnNewsFeed = new JButton("News Feed");
		btnNewsFeed.setBounds(661, 49, 97, 25);
		add(btnNewsFeed);
		btnNewsFeed.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				container.replace(new NewsFeedPanel(emailUser, container));
			}
			
		});
		
		
		if(emailUser.equals(emailName)){
		textField = new JTextField("What's on your mind?");
		textField.setBounds(12, 60, 300, 32);
		add(textField);
		textField.setColumns(10);
		textField.addFocusListener(new FocusListener() {

	        public void focusGained(FocusEvent e) {
	            if (textField.getText().equals("What's on your mind?")) {
	            	textField.setText("");
	            }
	        }

	        public void focusLost(FocusEvent e) {
	            if ("".equalsIgnoreCase(textField.getText().trim())) {
	            	textField.setText("What's on your mind?");
	            }
	        }});
		
		JButton btnNewButton = new JButton("Post Status");
		btnNewButton.setBounds(312, 60, 97, 32);
		add(btnNewButton);
		
		
		//=====================================//
		btnNewButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				String message = textField.getText();
				//message must be less than 150 chars
				if (message.length()>150)
				{
					JOptionPane.showMessageDialog(container,
							"The desired status post is too long.  Statuses cannot " +
							"be more than 150 characters,",
							"Status Post Too Long", JOptionPane.PLAIN_MESSAGE);
				}
				else
				{
					Post post = new Post(emailUser, message, new Date()); //Date() gives current time
					container.getController().postMessage(emailUser, post, true);
					JOptionPane.showMessageDialog(container, "Your status has" +
							" been posted!  Reload the page to see it",
							"Status posted", JOptionPane.PLAIN_MESSAGE);
					textField.setText("What's on your mind?");//reset box to default
				}
			}
			
		});
		//=====================================//

		
		
		JButton btnNewButton1 = new JButton("Post Notification");
		btnNewButton1.setBounds(409, 60, 140, 32);
		add(btnNewButton1);
		
		
		//=====================================//
		btnNewButton1.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				String message = textField.getText();
				//message can't be longer than 150 chars
				if (message.length()>150)
				{
					JOptionPane.showMessageDialog(container,
							"The desired notification is too long.  Notifications cannot " +
							"be more than 150 characters,",
							"Notification Too Long", JOptionPane.PLAIN_MESSAGE);
				}
				else
				{
					Post post = new Post(emailUser, message, new Date()); //Date() gives current time
					container.getController().postMessage(emailUser, post, false);
					JOptionPane.showMessageDialog(container, "Your notifcation has" +
							" been posted!  Reload the page to see it",
							"Status posted", JOptionPane.PLAIN_MESSAGE);
					textField.setText("What's on your mind?"); //reset text to default
				}
			}
			
		});
		//=====================================//

		
		}
	}
}
